const { Service } = require("egg");

class BannerService extends Service {
  async list() {
    return await this.app.model.Banner.findAll(
      {
        raw: true,
      },
      {
        logging: console.log,
      }
    );
  }
  async create(data) {
    const { title, linkUrl, bannerUrl } = data;
    

    return await this.app.model.Banner.create({
      title,
      linkUrl,
      bannerUrl,
    });
  }

  async delete(id) {
    return await this.app.model.Banner.destroy({
      where: { id },
    });
  }

  async update(data) {
    const { title, linkUrl, bannerUrl, id } = data;

    const bannerInfo = await this.app.model.Banner.findOne({
      where: { id },
    });
    if (bannerInfo) {
      const params = {};
      if (title) {
        params.title = title;
      }
      if (linkUrl) {
        params.linkUrl = linkUrl;
      }
      if (bannerUrl) {
        params.bannerUrl = bannerUrl;
      }
      const updatedBanner = await this.app.model.Banner.update(params, {
        where: { id: id },
      });
      return updatedBanner[0] ? updatedBanner[0] : null;
    }
    return null;
  }
}

module.exports = BannerService;
